package com.njwt.cloud.mszuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.xml.bind.DatatypeConverter;


/**
 * @author <a href="mailto:xingxiaofeng@gtmap.cn">xingxiaofeng</a>
 * @date 2022-05-08
 * @desc TrackingFilter
 */
@Component
public class TrackingFilter extends ZuulFilter {
    private static final int      FILTER_ORDER =  1;
    private static final boolean  SHOULD_FILTER=true;

    private static final Logger logger = LoggerFactory.getLogger(TrackingFilter.class);

    @Autowired
    private FilterUtils filterUtils;

    @Override
    public String filterType() {
        return FilterUtils.PRE_FILTER_TYPE;
    }

    @Override
    public int filterOrder() {
        return FILTER_ORDER;
    }
   @Override
    public boolean shouldFilter() {
        return SHOULD_FILTER;
    }

    private boolean isCorrelationIdPresent(){
        if (filterUtils.getCorrelationId() !=null){
            return true;
        }

        return false;
    }

    private String generateCorrelationId(){
        return java.util.UUID.randomUUID().toString();
    }
    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
     //   getToken();
        if (isCorrelationIdPresent()) {
            logger.debug("tmx-correlation-id found in tracking filter: {}. ", filterUtils.getCorrelationId());
        }
        else{
          //  filterUtils.setCorrelationId(generateCorrelationId());
            logger.debug("tmx-correlation-id generated in tracking filter: {}.", filterUtils.getCorrelationId());
        }

        return null;
    }
    private String getToken(){
        String result="";
        if(filterUtils.getAuthToken()!=null) {
            String authToken = filterUtils.getAuthToken().replace("Bearer ", "");
            if (authToken != null) {
                try {
                    Claims body = Jwts.parser().setSigningKey("123").parseClaimsJws(authToken).getBody();
                    String subject= body.getSubject();
                    System.out.println("subject:\n"+subject);
                } catch (Exception ex) {

                }
            }
        }
        return result;
    }
}
